import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2024-12-30
 * Time: 11:04
 */
class Solution3 {
    int[] index;
    int[] ret;
    int[] tmp;// 中间数组得搞两个分别记录数值和下标
    int[] tmpIndex;

    public List<Integer> countSmaller(int[] nums) {
        // 这道题的核心在于，需要的原下标下更改数值，创建一个index数组保存下标
        // 准备工作
        int n = nums.length;

        tmp = new int[n];
        index = new int[n];
        ret = new int[n];
        tmpIndex = new int[n];

        for (int i = 0; i < n; i++) {
            index[i] = i;
        }

        mergeSort(nums, 0, n - 1);

        List<Integer> l = new ArrayList<>();
        for (int j = 0; j < n; j++) {
            l.add(ret[j]);
        }
        return l;

    }

    public void mergeSort(int nums[], int left, int right) {
        if (left >= right) {
            return;
        }
        int mid = (left + right) / 2;

        mergeSort(nums, left, mid);
        mergeSort(nums, mid + 1, right);

        // [left , mid] [mid + 1 , right];

        int cur1 = left, cur2 = mid + 1, i = 0;// 降序
        while (cur1 <= mid && cur2 <= right) {
            if (nums[cur1] > nums[cur2]) {
                tmp[i] = nums[cur1];
                ret[index[cur1]] += right - cur2 + 1; // 可能原来的位置上已经有数值了，所以是+=
                tmpIndex[i++] = index[cur1++];
            } else if (nums[cur1] <= nums[cur2]) {
                tmp[i] = nums[cur2];
                tmpIndex[i++] = index[cur2++];// 记录这个元素原来的下标,放到中转下标数组中
            }
        }
        while (cur1 <= mid) {
            tmp[i] = nums[cur1];
            tmpIndex[i++] = index[cur1++];
        }
        while (cur2 <= right) {
            tmp[i] = nums[cur2];
            tmpIndex[i++] = index[cur2++];
        }
        // 合并数组(元素和下标都要合并)
        for (int j = left; j <= right; j++) {
            nums[j] = tmp[j - left];
            index[j] = tmpIndex[j - left];
        }

    }
}
public class Test3 {
}
